#include "crequestget.h"

CRequestGet::CRequestGet(QObject* parent)
    :QObject(parent)
{
    m_pListReply = NULL;
    m_pXMLDocument = NULL;
}

CRequestGet::~CRequestGet()
{
    if(m_pXMLDocument != NULL)
    {
        delete m_pXMLDocument;
        m_pXMLDocument = NULL;
    }

    if ( m_pListReply != NULL )
    {
        delete m_pListReply;
    }
}

bool CRequestGet::isReplyStringRight(   QString* pErrorStr,\
                                        int *pErrorLine,\
                                        int *pErrorColumn)
{
    if(m_pXMLDocument != NULL)
        delete m_pXMLDocument;

    m_pXMLDocument = new QDomDocument;

    if (!m_pXMLDocument->setContent(m_xmlString, true, pErrorStr, pErrorLine, pErrorColumn))
    {
        delete m_pXMLDocument;
        m_pXMLDocument = NULL;
        return false;
    }

    QDomElement root = m_pXMLDocument->documentElement();

    if (root.tagName() != "taxi")
    {
        return false;
    }

    if (root.attribute("command") != QString::number(m_commandID) )
    {
        return false;
    }

    return true;
}

const QString CRequestGet::getResult(QString key)
{
    return m_result.value(key);
}


int CRequestGet::getCommandID()
{
    return m_commandID;
}

QList<QString>& CRequestGet::getInteresedItemList()
{
    return m_interestedList;
}

QMultiMap<QString, QString>& CRequestGet::getResult()
{
    return m_result;
}

const QString CRequestGet::getReplyErrorString()
{
    if (m_pListReply != NULL)
    {
        return m_pListReply->errorString();
    }

    return QString("no reply has been set");
}

void CRequestGet::deleteReply()
{
    if (m_pListReply == NULL)
        return;

    delete m_pListReply;
    m_pListReply = NULL;
}

 bool CRequestGet::sendRequest(QObject *signalReciever, QString ipAddress, QString* arg, int count)
 {
     if (m_ArgCount != count)
         return false;


     QString urlString("http://");
     urlString.append(ipAddress);
     urlString.append("/");

     for(int i = 0; i < count; i++)
     {
         urlString.append(arg[i]);
     }

     QUrl url(urlString);

     QNetworkRequest req(url);

     // delete the former Reply
     if ( m_pListReply != NULL )
     {
         delete m_pListReply;
         m_pListReply = NULL;
     }
     m_pListReply = m_networkAccessManager->get(req);



     connect(m_pListReply,
             SIGNAL(downloadProgress(qint64, qint64)),
             signalReciever,
             SLOT(downloadProgress(qint64, qint64)));
     connect(m_pListReply,
             SIGNAL(finished()),
             signalReciever,
             SLOT(downloadFinished()));
     connect(m_pListReply,
             SIGNAL(error(QNetworkReply::NetworkError)),
             signalReciever,
             SLOT(downloadError(QNetworkReply::NetworkError)));

     return true;
 }
